package com.arcbbs.service.impl;

import com.arcbbs.constant.BaseConstant;
import com.arcbbs.entity.*;
import com.arcbbs.enums.FileUploadTypeEnum;
import com.arcbbs.enums.UserIntegralOperTypeEnum;
import com.arcbbs.exception.BaseException;
import com.arcbbs.mapper.FormArticleMapper;
import com.arcbbs.mapper.ForumCommentMapper;
import com.arcbbs.mapper.UserInfoMapper;
import com.arcbbs.mapper.UserMessageMapper;
import com.arcbbs.result.PageResult;
import com.arcbbs.service.ForumCommentService;
import com.arcbbs.service.UserInfoService;
import com.arcbbs.service.UserMessageService;
import com.arcbbs.utils.FileUtils;
import com.arcbbs.utils.StringTools;
import com.arcbbs.utils.SysCacheUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ForumCommentServiceImpl implements ForumCommentService {
    @Resource
    private ForumCommentMapper forumCommentMapper;

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserMessageMapper userMessageMapper;
    @Resource
    private FileUtils fileUtils;

    @Override
    public Integer findCountByParam(ForumCommentQuery param) {
        return forumCommentMapper.selectCount(param);
    }

    @Override
    public List<ForumComment> findListByParam(ForumCommentQuery param) {
        List<ForumComment> list = forumCommentMapper.selectList(param);
        if (param.getLoadChildren() != null && param.getLoadChildren()) {
            ForumCommentQuery subquery = new ForumCommentQuery();
            subquery.setQueryLikeType(param.getQueryLikeType());
            subquery.setCurrentUserId(param.getCurrentUserId());
            subquery.setArticleId(param.getArticleId());
            subquery.setLoadChildren(param.getLoadChildren());
            subquery.setStatus(param.getStatus());
            subquery.setOnlyQueryChildren(true);
            List<Integer> pcommentList = list.stream().map(ForumComment::getCommentId).distinct().collect(Collectors.toList());
            subquery.setSetPCommentIdList(pcommentList);
            List<ForumComment> subcommentList = forumCommentMapper.selectList(subquery);
            Map<Integer, List<ForumComment>> tempMap = subcommentList.stream().collect(Collectors.groupingBy(ForumComment::getpCommentId));
            System.out.println(tempMap);
            list.forEach(item -> {
                System.out.println(item.getpCommentId() + "item");
                item.setChildren(tempMap.get(item.getCommentId()));
            });
        }
        return list;
    }

    @Override
    public ForumComment getForumCommentById(Integer commentId) {
        return forumCommentMapper.getbyid(commentId);
    }

    @Resource
    private FormArticleMapper formArticleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changetoptype(String userId, Integer commentId, Integer topType) {
        ForumComment forumComment = forumCommentMapper.getbyid(commentId);
        if (forumComment == null) {
            throw new BaseException("评论不存在");
        }
        ForumArticleVo forumArticle = formArticleMapper.getbyid(forumComment.getArticleId());
        if (forumArticle == null) {
            throw new BaseException("文章不存在");

        }
        if (!forumArticle.getUserId().equals(userId) || forumComment.getpCommentId() != 0) {
            throw new BaseException("不是一级评论");
        }
        if (forumComment.getTopType().equals(topType)) {
            return;
        }
        //置顶，取消置顶
        if (topType.equals(1)) {
            forumCommentMapper.updateTopbyarticle(forumArticle.getArticleId());
        }
        ForumComment forumComment1 = new ForumComment();
        forumComment1.setTopType(topType);
        forumCommentMapper.updatebyud(topType, commentId);
    }

    @Resource
    private UserInfoMapper userInfoMapper;

    public void postcomment(ForumComment forumComment, MultipartFile image) {
        ForumArticleVo forumArticle = formArticleMapper.getbyid(forumComment.getArticleId());
        //判断文章，如果不是一级评论判断回复的评论是否存在，如果回复评论，判断回复的客户是否存在，如果存在设置回复的昵称
        if (forumArticle == null || forumArticle.getStatus().equals(0)) {
            throw new BaseException("文章不存在");

        }
        ForumComment pcomment = null;
        System.out.println(forumComment.getpCommentId());
        if (forumComment.getpCommentId() != 0) {
            pcomment = forumCommentMapper.getbyid(forumComment.getpCommentId());
            if (pcomment == null) {
                throw new BaseException("回复的评论不存在");
            }
        }
        if (!StringTools.isEmpty(forumComment.getReplyUserId())) {
            UserInfo userInfo = userInfoMapper.selectbyuserid(forumComment.getReplyUserId());
            if (userInfo == null) {
                throw new BaseException("回复的用户不存在");
            }
            forumComment.setReplyNickName(userInfo.getNickName());

        }
        forumComment.setPostTime(new Date());
        if (image != null) {
            FileUploadDto fileUploadDto= fileUtils.uploadDto(image,FileUploadTypeEnum.COMMENT_IMAGE);
            System.out.println(fileUploadDto.getLocalpath()+"fileuploaddto");
       forumComment.setImgPath(fileUploadDto.getLocalpath());
        }
        Boolean needAudit = SysCacheUtils.getSysSetting().getSystemSettingAduitDto().getCommentAudit();
        forumComment.setStatus(needAudit ? 0 : 1);
        forumCommentMapper.insert(forumComment);

        if (needAudit) {
            return;
        }
        updaetCommentInfo(forumComment,forumArticle,pcomment);

    }
@Resource
private UserMessageService userMessageService;
    public void updaetCommentInfo(ForumComment forumComment, ForumArticleVo forumArticle, ForumComment pcomment) {
        Integer commentIntegral = SysCacheUtils.getSysSetting().getSystemSettingCommentDto().getCommentIntegral();
        if (commentIntegral > 0) {
            userInfoMapper.updateIntegral(forumComment.getUserId(), commentIntegral);

        }
        if (forumComment.getpCommentId() == 0) {
            formArticleMapper.updateArticleNumber(2, 1, forumComment.getArticleId());

        }
        //记录消息
        UserMessage userMessage=new UserMessage();
        userMessage.setMessageType(1);
        userMessage.setCreateTime(new Date());
        userMessage.setArticleId(forumComment.getArticleId());
        userMessage.setCommentId(forumComment.getCommentId());
        userMessage.setSendUserId(forumComment.getUserId());
        userMessage.setSendNickName(forumComment.getNickName());
        userMessage.setStatus(0);
        userMessage.setArticleTitle(forumArticle.getTitle());
        if(forumComment.getCommentId() == 0){
            userMessage.setReceivedUserId(forumArticle.getUserId());


        }else if(forumComment.getpCommentId()!=0&&StringTools.isEmpty(forumComment.getReplyUserId())){
            userMessage.setReceivedUserId(pcomment.getUserId());
        }else if(forumComment.getpCommentId()!=0 && !StringTools.isEmpty(forumComment.getReplyUserId())){
            userMessage.setReceivedUserId(forumComment.getReplyUserId());

        }
        if(!forumComment.getUserId().equals(userMessage.getReceivedUserId())){
            userMessageMapper.insert(userMessage);
        }
    }
    public PageResult selectbypage(Integer pageNo){
        PageHelper.startPage(pageNo, 10);
        Page<ForumComment> list=forumCommentMapper.selectbypage();
        long total = list.getTotal();
        List<ForumComment> list1=list.getResult();
        return new PageResult(total,list1);
    }
}

